<?php

/**
 * 控制器基类
 */
class baseAction extends Action
{
    
     protected $uploadPath;
    protected $uploadPathSub;
    
    protected function _initialize()
    {
        //消除所有的magic_quotes_gpc转义        
        Input::noGPC();
        //初始化网站配置
//           $this->assign('server', $_SERVER);
//        $this->assign('Think', array(
//            'get'     => $_GET,
//            'post'    => $_POST,
//            'request' => $_REQUEST,
//            'server'  => $_SERVER,
//            'cookie'  => $_COOKIE,
//            'session' => $_SESSION,
//        ));
 
        $this->uploadPathSub = date("/Y/m/d/");
        $this->uploadPath    = './upload/assets' . $this->uploadPathSub;
    }
    
        function update_config($new_config, $config_file = '') {
               !is_file($config_file) && $config_file =CONF_PATH . '/config.php';
               if (is_writable($config_file)) {
               $config = require $config_file;
               $config = array_merge($config, $new_config);
               file_put_contents($config_file, "<?php \nreturn " . stripslashes(var_export($config, true)) . ";", LOCK_EX);
               @unlink(RUNTIME_FILE);
               return true;
               } else {
               return false;
               }
           }
           
            /**
     * 上传文件默认规则定义
     */
    protected function _upload_init($upload)
    {
        $allow_max  = C('ins_attr_allow_size'); //读取配置
        $allow_exts = explode(',', C('ins_attr_allow_exts')); //读取配置
        $allow_max && $upload->maxSize = $allow_max * 1024; //文件大小限制
        $allow_exts && $upload->allowExts = $allow_exts; //文件类型限制
        $upload->saveRule = 'uniqid';
        return $upload;
    }

    protected function uploadFile($content)
    {
         $siteRoot = C('__SITEROOT__');
        $saveDir   = C('ASSETS_DIR_RULE');
        $urlPrefix = 'http://' . $_SERVER['HTTP_HOST'] . '/upload/assets';
        if (strpos($content, $urlPrefix) === 0) {
            $res      = substr($content, strlen($urlPrefix));
            $saveDir  = substr($res, 0, strrpos($res, '/') + 1);
            $saveName = substr($res, strrpos($res, '/') + 1);
        }
        else if (preg_match('/^\/(\d+)\/(\d+)\/(\d+)\//', $content) > 0) {
            $saveDir  = substr($content, 0, strrpos($content, '/') + 1);
            $saveName = substr($content, strrpos($content, '/') + 1);
        }
        else {
            $saveName = uniqid() . '.jpg';
            $path     = rtrim(C('ins_attach_path'), '/') . '/assets' . $saveDir;
            mkdir($path, 0777, true);

            file_put_contents($path . $saveName, _base64_decode($content));
            imageThumb($path . $saveName);
        }

        $data = array(
            'saveDir'  => $saveDir,
            'savePath' => $saveDir . $saveName,
            'fullPath' => $siteRoot . '/upload/assets' . $saveDir . $saveName,
        );
        return compact('data');
    }

    /**
     * 上传文件
     */
    protected function _upload($file, $thumb = array(), $save_rule = 'uniqid')
    {
        
        $saveDir = C('ASSETS_DIR_RULE');
        $siteRoot = C('__SITEROOT__');
        
        import("@.ORG.UploadFile");
        $upload           = new UploadFile();
        $upload->savePath = rtrim(C('ins_attach_path'), '/') . '/assets' . $saveDir;
        
//       return print_r($siteRoot);

        mkdir($upload->savePath, 0777, true);
        //判断上传图片是否缩略
        if ($thumb) {
            $upload->thumb             = true;
            $upload->thumbMaxWidth     = $thumb['width'];
            $upload->thumbMaxHeight    = $thumb['height'];
            $upload->thumbPrefix       = '';
            $upload->thumbSuffix       = isset($thumb['suffix']) ? $thumb['suffix'] : '_thumb';
            $upload->thumbExt          = isset($thumb['ext']) ? $thumb['ext'] : '';
            $upload->thumbRemoveOrigin = isset($thumb['remove_origin']) ? true : false;
        }
        //自定义上传规则
       $upload = $this->_upload_init($upload);

        if ($result = $upload->uploadOne($file)) {
            $data = array();
//            foreach ($result as $key => $val) {
//                $savePath = $result[$key]['savepath'] = trim($val['savepath'], '/') . '/';
//                if (empty($this->uploadCropData)) {
//                    $cropData = $_GET('cropData');
//                }
//                else {
//                    $cropData = $this->uploadCropData[$key];
//                }
//                if (strpos($savePath, '/assets/') > 0) {
//                    imageThumb($savePath . $val['savename'], json_decode(base64_decode($cropData)));
//                }
//                $data [] = array(
//                    'saveDir'  => $saveDir,
//                    'savePath' => $saveDir . $val['savename'],
//                    'fullPath' =>$siteRoot . '/upload/assets' . $saveDir . $val['savename'],
//                );
//            }
            $result = array('error' => 0, 'info' => $result, 'data' => $data);
        }
        else {
            
            $result = array('error' => 1, 'info' => $upload->getErrorMsg());
        }
        $this->uploadCropData = array();
        return $result;
    }

    /**
     * 请求接口封装  get/post/put/delete等
     * access public
     * @param string $url 接口地址
     * @param string $params 参数
     * @param string $type 类型 get/post/put/delete
     * @return bool/array
     */
     public function getcurldata($url,$params,$type="get"){
        $url = $this->serverhost.$url;
  
        $response = array();
        if($type == 'get'){ //get请求
          //请求头可以加其他设置
          $headers = array(
              'Content-type: application/json;charset=UTF-8',
          );
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $response = curl_exec($ch);
  
       }elseif ($type == 'post'){  //post请求
  
         $headers = array(
            'Content-type: application/json;charset=UTF-8',
         );
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
         curl_setopt($ch, CURLOPT_POST, true);  //注意这几行
         curl_setopt($ch, CURLOPT_POSTFIELDS, $params); //注意这几行
         //curl_setopt($ch, CURLOPT_HEADER, true);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         $response = curl_exec($ch);
  
       }elseif ($type == 'put'){ //put请求
  
          $headers = array(
               'Content-type: application/json;charset=UTF-8',
          );
  
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
          curl_setopt($ch, CURLOPT_PUT, true); //注意这几行
          curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
          //curl_setopt($ch, CURLOPT_HEADER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
          $response = curl_exec($ch);
       }
  
       return $response;
    } 
  
}